<template>
  <div class="app-container">
    <!-- 输入表单 -->
    <el-form label-width="120px">
      <el-form-item label="讲师名称">
        <el-input v-model="teacher.name" />
      </el-form-item>
      <el-form-item label="入驻时间">
        <el-date-picker v-model="teacher.joinDate" value-format="yyyy-MM-dd" />
      </el-form-item>
      <el-form-item label="讲师排序">
        <el-input-number v-model="teacher.sort" :min="0" />
      </el-form-item>
      <el-form-item label="讲师头衔">
        <el-select v-model="teacher.level">
          <!--
                数据类型一定要和取出的json中的一致，否则没法回填
                因此，这里value使用动态绑定的值，保证其数据类型是number
                -->
          <el-option :value="1" label="高级讲师" />
          <el-option :value="2" label="首席讲师" />
        </el-select>
      </el-form-item>
      <el-form-item label="讲师资历">
        <el-input v-model="teacher.career" />
      </el-form-item>
      <el-form-item label="讲师简介">
        <el-input v-model="teacher.intro" :rows="10" type="textarea" />
      </el-form-item>

      <!-- 讲师头像 -->
      <el-form-item label="上传头像">
        <el-upload class="avatar-uploader" action="http://vcourse-file-1.oss-cn-hangzhou.aliyuncs.com" :show-file-list="false"
          :data="dataObj" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-error="handleError">
          <img v-if="teacher.avatar" :src="teacher.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate()">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {
    save,
    update,
    getById
  } from '@/api/teacher'
  import {
    uploadPolicy,
    deleteAvatar
  } from '@/api/oss'
  import {
    getUUID
  } from '@/utils/myfun'
  export default {
    data() {
      return {
        // 讲师信息
        teacher: {},
        // 防止表单重复提交
        savaBtnDisabled: false,
        // 文件上传请求的签名信息
        dataObj: {
          key: '',
          policy: '',
          OSSAccessKeyId: '',
          success_action_status: '',
          signature: ''
        }
      }
    },
    created() {
      if (this.$route.params.id) {
        this.getData(this.$route.params.id)
      }
    },
    methods: {
      saveOrUpdate() {
        this.savaBtnDisabled = true
        if (this.teacher.id) {
          this.updateDate()
        } else {
          this.saveDate()
        }
      },
      // 新增数据
      saveDate() {
        save(this.teacher).then(response => {
          // 弹出成功提示
          this.$message({
            message: response.message,
            type: 'success'
          })
          // 跳转到讲师列表
          this.$router.push({
            path: '/teacher/list'
          })
        })
      },
      // 编辑数据
      updateDate() {
        update(this.teacher).then(response => {
          // 弹出成功提示
          this.$message({
            message: response.message,
            type: 'success'
          })
          // 跳转到讲师列表
          this.$router.push({
            path: '/teacher/list'
          })
        })
      },
      // 编辑时查询讲师信息，回显
      getData(id) {
        getById(id).then(response => {
          this.teacher = response.data
        })
      },
      // 文件上传成功
      handleAvatarSuccess(res, file) {
        this.teacher.avatar = this.dataObj.host + '/' + this.dataObj.key
        // 强制重新渲染
        this.$forceUpdate()
      },
      // 文件上传前校验
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
          return false
        } else {
          let dir = 'avatar'
          let _self = this;
          // 请求签名(必须使用Promise，要不然dataObj无法及时绑定)
          return new Promise((resolve, reject) => {
            uploadPolicy(dir).then(response => {
              // 设置文件的完整路径
              _self.dataObj.key = response.data.dir + '/' + getUUID() + file.name
              _self.dataObj.policy = response.data.policy
              _self.dataObj.signature = response.data.signature
              _self.dataObj.OSSAccessKeyId = response.data.accessid
              _self.dataObj.dir = response.data.dir
              _self.dataObj.host = response.data.host
              _self.dataObj.success_action_status = '200'
              resolve(true)
            }).catch(err => {
              reject(false)
            })
            console.log(this.dataObj)
          })
        }
      },
      // 文件上传失败(http)
      handleError(err, file) {
        console.log('文件上传失败')
        // 弹出成功提示
        this.$message.error(err)
      },
      // 文件删除
      handleRemove(file) {
        console.log(file.url)
        // deleteAvatar(file.url).then(response => {
        //   this.teacher.avatar = ''
        // })
      }
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
